import { useRequest } from "ahooks";
import axios from "axios";
import { GET_USERS } from "./api/userApi";
import { useEffect } from "react";
import {
  addUser,
  deleteUser,
  getUsers,
  updateUser,
} from "./store/slice/userSlice";
import { useDispatch, useSelector } from "react-redux";

interface user {
  id: number;
  name: string;
  age: number;
}
function ReduxIndex() {
  const dispatch = useDispatch();
  const {
    users: data,
    status,
    error,
  } = useSelector((state: any) => state.user);
  // query
  useEffect(() => {
    dispatch(getUsers());
  }, [dispatch]);

  // add
  const add = () => {
    dispatch(addUser({ name: "张三", age: 18 }));
  };
  // edit
  const edit = () => {
    dispatch(updateUser({ id: 1, name: "李四", age: 20 }));
  };
  // del
  const del = () => {
    dispatch(deleteUser({ id: 1 }));
  };
  return (
    <>
      {status}
      <ul>
        {data?.map((user: { id: number; name: string; age: number }) => (
          <li key={user.id}>
            姓名: {user.name}, 年龄: {user.age}
          </li>
        ))}
      </ul>
      <button
        onClick={() => {
          add();
        }}
      >
        添加用户
      </button>
      <button
        onClick={() => {
          edit();
        }}
      >
        修改用户
      </button>
      <button
        onClick={() => {
          del();
        }}
      >
        删除用户
      </button>
    </>
  );
}

export default ReduxIndex;
